package com.leinbo.onedoc.utils

import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.io.OutputStream
import java.net.HttpURLConnection
import java.net.URL


/**
 * Created by sundaiyue on 2022/11/23 15:07
 */
object DownloadUtil {
    //下载链接  下载到的目录  下载后的文件名称
    @Throws(Exception::class)
    fun download(url: URL, targetDirectory: String, fileName: String): File? {
        if (File(targetDirectory).exists().not()) {
            File(targetDirectory).mkdirs()
        }
        // 解决url中可能有中文情况
        val http: HttpURLConnection = url.openConnection() as HttpURLConnection
        http.connectTimeout = 3000
        // 设置 User-Agent 避免被拦截
        http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.license.xml; Trident/5.0)")
        val contentType: String = http.contentType
        // 获取文件大小
        val length: Long = http.contentLengthLong
        // 获取文件名
        val inputStream: InputStream = http.inputStream
        val buff = ByteArray(1024 * 10)
        val file = File(targetDirectory, fileName)
        if (!file.exists()) {
            val out: OutputStream = FileOutputStream(file)
            var len: Int
            var count = 0 // 计数
            while (inputStream.read(buff).also { len = it } != -1) {
                out.write(buff, 0, len)
                out.flush()
                ++count
            }
            // 关闭资源
            out.close()
            inputStream.close()
            http.disconnect()
            return File(targetDirectory, fileName)
        }
        return null
    }
}
